package cn.itqiqi.student_system_java.service.impl;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.jwt.JWT;
import cn.itqiqi.student_system_java.mapper.UserMapper;
import cn.itqiqi.student_system_java.pojo.User;
import cn.itqiqi.student_system_java.service.UserService;
import cn.itqiqi.student_system_java.utils.JWTUtils;
import cn.itqiqi.student_system_java.utils.ResultUtils;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.TreeMap;

/**
 * @author kevin_琪琪
 * @version 1.0
 * @description
 * @date 2022-06-20 09:23
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ResultUtils resultUtils;
    private final TreeMap<String, String> tokenMap = new TreeMap<>();

    @Override
    public String login(String username, String password) {
        List<User> userList = userMapper.getUserList();
        for (User user : userList) {
            if (user.getUsername().equals(username)) {
                if (user.getPassword().equals(password)) {
                    tokenMap.clear();
                    tokenMap.put("username", user.getUsername());
                    String token = JWTUtils.getToken(tokenMap);
                    return resultUtils.success(token, "登录成功！");
                } else {
                    return resultUtils.fail(403, "用户名或密码错误！");
                }
            }
        }
        return resultUtils.fail(403, "用户不存在！");
    }

    @Override
    public String loginVerify(String token) {
        try{
            JWTUtils.verify(token);//验证令牌
            return resultUtils.success("登录成功!");//放行请求
        } catch (TokenExpiredException e) {
            String username = JWT.of(token).getPayload("username").toString();
            tokenMap.clear();
            tokenMap.put("username", username);
            String resToken = JWTUtils.getToken(tokenMap);
            return resultUtils.success(210, resToken, "登录成功!");
        } catch (Exception e) {
            return resultUtils.fail(400, "登录信息已过期!");
        }
    }

    @Override
    public User getUserByUserName(String username) {
        return userMapper.getUserByUserName(username);
    }
}
